// https://docs.rs/winit/0.30.5/winit/
use winit::event_loop::{ActiveEventLoop};
use winit::application::ApplicationHandler;
use winit::event::{KeyEvent, WindowEvent,ElementState};
use winit::window::{Window, WindowId};
use winit::keyboard::{Key, NamedKey};

use std::sync::Arc;
use crate::context::Context; // 引入contex模块    

// winit 0.30 以上版本使用：https://zhuanlan.zhihu.com/p/697751367

// 添加 Default 以便App::default()来快速创建App实例
#[derive(Default)]
pub struct App<'a> {
    window: Option<Arc<Window>>,
    context: Option<Context<'a>>,
    flag: bool,// 用于回车控制surface尺寸的切换标志
}

impl<'a> ApplicationHandler for App<'a> {
    fn resumed(&mut self, event_loop: &ActiveEventLoop) {
// 考虑多平台可以移植性，推荐建议应用程序在收到第一个 Resumed 事件后仅初始化其图形上下文并创建窗口
        // 避免重复创建窗口
        if self.window.is_none() {
            let win_attr = Window::default_attributes().with_title("绘制三角形");
            // use Arc
            let window = Arc::new(
                event_loop.create_window(win_attr)
                .expect("Failed to create window"));
            self.window = Some(window.clone());
            self.context = Some(Context::new(window.clone()));

        }

    }

    fn window_event(&mut self, event_loop: &ActiveEventLoop, _window_id: WindowId, event: WindowEvent) {
        match event {
            WindowEvent::CloseRequested => {
                println!("The close button was pressed; stopping");
                event_loop.exit();
            },
            WindowEvent::Resized(size) => {
                if let (Some(contex), Some(window)) =
                    (self.context.as_mut(), self.window.as_ref())
                {
                    contex.resize(size.width, size.height);
                    window.request_redraw();
                }
            },  
            WindowEvent::KeyboardInput {
                event:KeyEvent {
                    repeat: false,  
                    state: ElementState::Pressed,
                    logical_key: Key::Named(NamedKey::Enter),
                    ..
                  },
                  ..
                } => {
                // 回车键按键事件下，来回切换表面尺寸为整个窗口尺寸或窗口宽高各1/2尺寸
                if let (Some(context), Some(window)) =
                    (self.context.as_mut(), self.window.as_ref())
                {
                    let size = window.inner_size();
                    let w = size.width.max(1);
                    let h = size.height.max(1);
                    if self.flag {
                        context.resize(w, h);
                    } else {
                        context.resize(w / 2, h / 2);
                    }
                    self.flag = !self.flag;
                    window.request_redraw();
                }

            },
            WindowEvent::RedrawRequested => {
                if let Some(context) = self.context.as_mut() {
                    context.draw();
                }
            },
            _ => (),
        }
    }
}
